package main

import (
	"flag"
	"github.com/gin-gonic/gin"

	"io"
	"log"
	"morleyStoneHome/config"
	"morleyStoneHome/dao"
	"morleyStoneHome/router"
	"net/http"
	"os"
	"time"

	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var webServer *http.Server
var configFile = flag.String("config", "./morley.yaml", "配置文件路径")

func init() {
	//解析启动参数，无参数则使用默认值
	flag.Parse()
	//读取配置文件
	conf := config.Init(*configFile)
	//初始化gorm
	gormConfig := &gorm.Config{}
	// 初始化日志
	if file, err := os.OpenFile(conf.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
		logrus.SetOutput(io.MultiWriter(os.Stdout, file))
		if conf.ShowSql {
			gormConfig.Logger = logger.New(log.New(file, "\r\n", log.LstdFlags), logger.Config{
				SlowThreshold: time.Second,
				Colorful:      true,
				LogLevel:      logger.Info,
			})
		}
	} else {
		logrus.SetOutput(os.Stdout)
		logrus.Error(err)
	}

	//初始化Gin和Controller路由
	routerDefault := gin.Default()
	//routerDefault.Use(middlewares.Cors())
	//routerDefault.Use(cors.New(cors.Config{
	//	AllowOrigins:     []string{"*"},
	//	AllowMethods:     []string{"PUT", "PATCH", "POST", "GET", "OPTIONS", "PUT", "DELETE", "UPDATE"},
	//	AllowHeaders:     []string{"*"},
	//	ExposeHeaders:    []string{"*"},
	//	AllowCredentials: true,
	//	AllowOriginFunc: func(origin string) bool {
	//		return true
	//	},
	//	MaxAge: 12 * time.Hour,
	//}))
	webServer = router.ConfigGin(conf.Port, routerDefault)
	router.ConfigRouter(routerDefault)
	//连接数据库
	//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"//conf.MySqlUrl
	dsn := conf.MySqlUrl
	logrus.Info("conf.mysql.url : ==== >", dsn)
	var gormConErr error
	dao.Db, gormConErr = gorm.Open(mysql.Open(dsn), gormConfig)
	if nil != gormConErr {
		logrus.Error(gormConErr)
	}
}

func main() {
	//go scheduler.Start()
	err := webServer.ListenAndServe()
	if err != nil {
		logrus.Error(err)
	}
}
